package com.kongjian.manage.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flk.component.client.common.ProtocolType;
import com.flk.component.client.common.exception.FlkCCSignException;
import com.flk.component.client.common.http.HttpClientConfig;
import com.flk.component.client.sign.FlkSvsClient;
import com.kongjian.manage.utils.JWTUtil;
import com.kongjian.manage.common.R;
import com.kongjian.manage.mapper.SysUserMapper;
import com.kongjian.manage.model.dto.LoginSysUserDTO;
import com.kongjian.manage.model.dto.LoginVerificationSysUserDTO;
import com.kongjian.manage.model.dto.NewSysUserDTO;
import com.kongjian.manage.model.dto.UpdateSysUserDTO;
import com.kongjian.manage.model.entity.SysUserEntity;
import com.kongjian.manage.model.query.SysUserQuery;
import com.kongjian.manage.model.vo.SysUserVO;
import com.kongjian.manage.service.ISysUserService;
import com.kongjian.manage.common.CustomException;
import com.kongjian.manage.utils.Sm4Util;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tangjunfeng
 * @Classname SysUserServiceImpl.java
 * @Description 用户管理service
 * @Date 2023-12-18
 * @Version V1.0
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements ISysUserService {


    @Resource
    private RestTemplate restTemplate;

    @Override
    public R<Page> queryPageSysUser(SysUserQuery query) throws Exception {
        //构造分页构造器
        Page pageInfo = new Page(query.getPage(), query.getSize());
        LambdaQueryWrapper<SysUserEntity> lambda = queryWhere(query);

        //执行查询
        Page result = this.page(pageInfo, lambda);
        return R.success(result);
    }

    @Override
    public SysUserVO getByIdSysUser(Long id) throws Exception {
        SysUserVO sysUserVO = new SysUserVO();
        SysUserEntity sysUserEntity = baseMapper.selectById(id);
        if (sysUserEntity != null) {
            BeanUtils.copyProperties(sysUserEntity, sysUserVO);
        }
        return sysUserVO;
    }

    @Override
    public void addSysUser(NewSysUserDTO sysUserDTO) throws Exception {
        SysUserEntity sysUser = new SysUserEntity();
        BeanUtils.copyProperties(sysUserDTO, sysUser);
        if (sysUserDTO.getCreateUser()== null){
            sysUser.setCreateUser(-1l);
        }
        if (sysUserDTO.getUpdateUser()== null){
            sysUser.setUpdateUser(-1l);
        }
        if (sysUserDTO.getCreateTime()== null){
            sysUser.setCreateTime(LocalDateTime.now());
        }
        String password = sysUserDTO.getPassword();
        // 调用密码机
        String pawd = Sm4Util.sm4Password(password);
        sysUser.setPassword(pawd);

        baseMapper.insert(sysUser);
    }

    @Override
    public void modifySysUser(Long id, UpdateSysUserDTO sysUserDTO) throws Exception {
        SysUserEntity sysUser = baseMapper.selectById(id);
        if (sysUser != null) {
            if (sysUserDTO.getUserId() != null) {
                sysUser.setUserId(sysUserDTO.getUserId());
            }
            if (sysUserDTO.getUsername() != null) {
                sysUser.setUsername(sysUserDTO.getUsername());
            }
            if (sysUserDTO.getPassword() != null) {
                sysUser.setPassword(sysUserDTO.getPassword());
            }
            if (sysUserDTO.getPhone() != null) {
                sysUser.setPhone(sysUserDTO.getPhone());
            }
            if (sysUserDTO.getAvatar() != null) {
                sysUser.setAvatar(sysUserDTO.getAvatar());
            }
            if (sysUserDTO.getNickname() != null) {
                sysUser.setNickname(sysUserDTO.getNickname());
            }
            if (sysUserDTO.getName() != null) {
                sysUser.setName(sysUserDTO.getName());
            }
            if (sysUserDTO.getEmail() != null) {
                sysUser.setEmail(sysUserDTO.getEmail());
            }
            if (sysUserDTO.getDeptId() != null) {
                sysUser.setDeptId(sysUserDTO.getDeptId());
            }
            if (sysUserDTO.getLockFlag() != null) {
                sysUser.setLockFlag(sysUserDTO.getLockFlag());
            }
            if (sysUserDTO.getDelFlag() != null) {
                sysUser.setDelFlag(sysUserDTO.getDelFlag());
            }
            baseMapper.updateById(sysUser);
        }
    }

    @Override
    public void deleteSysUser(Long id) throws Exception {
        SysUserEntity sysUserEntity = baseMapper.selectById(id);
        if (sysUserEntity == null) {
            throw new CustomException("id:" + id + "没有查到数据");
        }
        baseMapper.deleteById(id);
    }

    @Override
    public Integer countSysUser(SysUserQuery query) {
        LambdaQueryWrapper<SysUserEntity> lambda = queryWhere(query);
        return Math.toIntExact(baseMapper.selectCount(lambda));
    }


    @Override
    public void login(LoginSysUserDTO loginSysUserDTO) {
        String username = loginSysUserDTO.getUsername();
        String password = loginSysUserDTO.getPassword();
        //使用SM4对身份进行鉴权。

        LambdaQueryWrapper<SysUserEntity> lambda = new LambdaQueryWrapper<>();
        lambda.eq(username != null, SysUserEntity::getUsername, username);
        SysUserEntity sysUserEntity = baseMapper.selectOne(lambda);
        if (sysUserEntity == null) {
            throw new CustomException("没有查到数据");
        }
        //数据库存储的加密密码
        String passwd = sysUserEntity.getPassword();
        //使用SM4加密后的密码
        String pass = Sm4Util.sm4Password(password);

        if (!passwd.equals(pass)) {
            throw new CustomException("密码不正确");
        }
    }

    @Override
    public void signature(LoginSysUserDTO loginSysUserDTO) {

        //http请求配置，请求连接数，连接超时时长，ssl配置等
        HttpClientConfig config = HttpClientConfig.getDefault("10.82.118.244");
        config.setProtocolType(ProtocolType.HTTP);
        config.setBaseUrl("/svs");
        FlkSvsClient svsClient = null;
        try {
            svsClient = new FlkSvsClient(config);
        } catch (FlkCCSignException e) {
            log.error(e.getMessage(), e);
        }

        //待签名的数据原文
        String s = svsClient.SOF_signData(loginSysUserDTO.getUsername().getBytes());
        System.out.println("签名返回：" + s);

    }

    @Override
    public String firstSignature(LoginSysUserDTO loginSysUserDTO) {
        //登录
        login(loginSysUserDTO);

        //签名
        signature(loginSysUserDTO);

        //生成随机数
        String randomStr = getRandomStr();

        return randomStr;
    }

    @Override
    public String secondVerification(LoginVerificationSysUserDTO loginSysUserDTO, HttpSession session) {
        //http请求配置，请求连接数，连接超时时长，ssl配置等
        HttpClientConfig config = HttpClientConfig.getDefault("10.82.118.244");
        config.setProtocolType(ProtocolType.HTTP);
        config.setBaseUrl("/svs");
        FlkSvsClient svsClient = null;
        try {
            svsClient = new FlkSvsClient(config);
        } catch (FlkCCSignException e) {
            log.error(e.getMessage(), e);
        }

        boolean s = svsClient.SOF_verifySignedData(loginSysUserDTO.getBase64EncodeCert(), loginSysUserDTO.getInData().getBytes(), loginSysUserDTO.getSignValue());
        System.out.println("签名返回：" + s);
        session.setAttribute("user", loginSysUserDTO.getUsername());

        //生成JWT返回给客户端
        Map<String, String> payload = new HashMap<>();
        payload.put("username", loginSysUserDTO.getUsername());
        // 生成token
        String token = JWTUtil.getToken(payload);

        return token;
    }

    /**
     * 获取随机数
     *
     * @return
     */
    public String getRandomStr() {

        //http请求配置，请求连接数，连接超时时长，ssl配置等
        HttpClientConfig config = HttpClientConfig.getDefault("10.82.118.244");
        config.setProtocolType(ProtocolType.HTTP);
        config.setBaseUrl("/svs");
        FlkSvsClient svsClient = null;
        try {
            svsClient = new FlkSvsClient(config);
        } catch (FlkCCSignException e) {
            log.error(e.getMessage(), e);
        }

        //待签名的数据原文
        String s = svsClient.SOF_genRandom((short) 6);
        return s;
    }


    private LambdaQueryWrapper<SysUserEntity> queryWhere(SysUserQuery query) {
        LambdaQueryWrapper<SysUserEntity> lambda = new LambdaQueryWrapper<>();
        lambda.eq(query.getUserId() != null, SysUserEntity::getUserId, query.getUserId());
        lambda.eq(query.getUsername() != null, SysUserEntity::getUsername, query.getUsername());
        lambda.eq(query.getPassword() != null, SysUserEntity::getPassword, query.getPassword());
        lambda.eq(query.getPhone() != null, SysUserEntity::getPhone, query.getPhone());
        lambda.eq(query.getAvatar() != null, SysUserEntity::getAvatar, query.getAvatar());
        lambda.eq(query.getNickname() != null, SysUserEntity::getNickname, query.getNickname());
        lambda.eq(query.getName() != null, SysUserEntity::getName, query.getName());
        lambda.eq(query.getEmail() != null, SysUserEntity::getEmail, query.getEmail());
        lambda.eq(query.getDeptId() != null, SysUserEntity::getDeptId, query.getDeptId());
        lambda.eq(query.getLockFlag() != null, SysUserEntity::getLockFlag, query.getLockFlag());
        lambda.eq(query.getDelFlag() != null, SysUserEntity::getDelFlag, query.getDelFlag());
        //添加排序条件
        lambda.orderByDesc(SysUserEntity::getUpdateTime);
        return lambda;
    }

}
